package com.freeter.modules.gjs.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.freeter.modules.gjs.entity.MstrDivision;
import com.freeter.modules.gjs.mapper.MstrDivisionMapper;
import com.freeter.modules.gjs.service.MstrDivisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.ArrayList;

@Service
public class MstrDivisionServiceImpl implements MstrDivisionService {
    @Autowired
    private MstrDivisionMapper mstrDivisionMapper;

    public List<MstrDivision> getDivisionsByCondition(String name, Integer state) {
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        if (name != null) wrapper.eq("name_en", name);
        if (state != null) wrapper.eq("is_deleted", state);
        return mstrDivisionMapper.selectList(wrapper);
    }

    @Override
    public List<MstrDivision> getAllDivisions() {
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        wrapper.eq("is_deleted", 0); // 只查询未删除的记录
        wrapper.orderBy("id", true); // 按ID升序排列
        return mstrDivisionMapper.selectList(wrapper);
    }

    @Override
    public MstrDivision getDivisionById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("Division ID cannot be null or negative");
        }
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        wrapper.eq("id", id).eq("is_deleted", 0);
        List<MstrDivision> divisions = mstrDivisionMapper.selectList(wrapper);
        return divisions.isEmpty() ? null : divisions.get(0);
    }

    @Override
    public MstrDivision getDivisionByCode(String divisionCode) {
        if (!StringUtils.hasText(divisionCode)) {
            throw new IllegalArgumentException("Division code cannot be null or empty");
        }
        // 由于实体类中没有divisionCode字段，这里使用nameEn作为替代
        // 如果需要按divisionCode查询，需要先修改实体类
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        wrapper.eq("name_en", divisionCode).eq("is_deleted", 0);
        List<MstrDivision> divisions = mstrDivisionMapper.selectList(wrapper);
        return divisions.isEmpty() ? null : divisions.get(0);
    }

    @Override
    public MstrDivision createDivision(MstrDivision division) {
        if (division == null) {
            throw new IllegalArgumentException("Division cannot be null");
        }
        if (!StringUtils.hasText(division.getNameEn())) {
            throw new IllegalArgumentException("Division English name cannot be null or empty");
        }
        
        // 检查是否已存在相同名称的部门
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        wrapper.eq("name_en", division.getNameEn()).eq("is_deleted", 0);
        List<MstrDivision> existingDivisions = mstrDivisionMapper.selectList(wrapper);
        if (!existingDivisions.isEmpty()) {
            throw new RuntimeException("Division with name '" + division.getNameEn() + "' already exists");
        }
        
        // 设置默认值
        division.setIsDeleted(0);
        
        // 插入记录
        int result = mstrDivisionMapper.insert(division);
        if (result <= 0) {
            throw new RuntimeException("Failed to create division");
        }
        
        return division;
    }

    @Override
    public MstrDivision updateDivision(Long id, MstrDivision division) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("Division ID cannot be null or negative");
        }
        if (division == null) {
            throw new IllegalArgumentException("Division cannot be null");
        }
        
        // 检查部门是否存在
        MstrDivision existingDivision = getDivisionById(id);
        if (existingDivision == null) {
            throw new RuntimeException("Division with ID " + id + " not found");
        }
        
        // 如果更新名称，检查是否与其他部门重复
        if (StringUtils.hasText(division.getNameEn()) && 
            !division.getNameEn().equals(existingDivision.getNameEn())) {
            Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
            wrapper.eq("name_en", division.getNameEn()).eq("is_deleted", 0).ne("id", id);
            List<MstrDivision> duplicateDivisions = mstrDivisionMapper.selectList(wrapper);
            if (!duplicateDivisions.isEmpty()) {
                throw new RuntimeException("Division with name '" + division.getNameEn() + "' already exists");
            }
        }
        
        // 设置ID和更新字段
        division.setId(id);
        
        // 执行更新
        int result = mstrDivisionMapper.updateById(division);
        if (result <= 0) {
            throw new RuntimeException("Failed to update division");
        }
        
        // 返回更新后的完整记录
        return getDivisionById(id);
    }

    @Override
    public void deleteDivision(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("Division ID cannot be null or negative");
        }
        
        // 检查部门是否存在
        MstrDivision existingDivision = getDivisionById(id);
        if (existingDivision == null) {
            throw new RuntimeException("Division with ID " + id + " not found");
        }
        
        // 软删除：设置is_deleted为1
        MstrDivision divisionToDelete = new MstrDivision();
        divisionToDelete.setId(id);
        divisionToDelete.setIsDeleted(1);
        
        int result = mstrDivisionMapper.updateById(divisionToDelete);
        if (result <= 0) {
            throw new RuntimeException("Failed to delete division");
        }
    }

    @Override
    public void deleteDivisionByCode(String divisionCode) {
        if (!StringUtils.hasText(divisionCode)) {
            throw new IllegalArgumentException("Division code cannot be null or empty");
        }
        
        // 先查询部门
        MstrDivision division = getDivisionByCode(divisionCode);
        if (division == null) {
            throw new RuntimeException("Division with code '" + divisionCode + "' not found");
        }
        
        // 调用ID删除方法
        deleteDivision(division.getId());
    }

    @Override
    public List<MstrDivision> getDivisionsByStatus(String status) {
        if (!StringUtils.hasText(status)) {
            throw new IllegalArgumentException("Status cannot be null or empty");
        }
        
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        if ("ACTIVE".equalsIgnoreCase(status) || "1".equals(status)) {
            wrapper.eq("is_deleted", 0);
        } else if ("DELETED".equalsIgnoreCase(status) || "0".equals(status)) {
            wrapper.eq("is_deleted", 1);
        } else {
            // 如果状态值不明确，返回空列表
            return new ArrayList<>();
        }
        
        wrapper.orderBy("id", true);
        return mstrDivisionMapper.selectList(wrapper);
    }
    
    // 新增的便捷方法
    public List<MstrDivision> getActiveDivisions() {
        return getDivisionsByStatus("ACTIVE");
    }
    
    public boolean isDivisionExists(Long id) {
        if (id == null || id <= 0) {
            return false;
        }
        return getDivisionById(id) != null;
    }
    
    public boolean isDivisionNameExists(String nameEn) {
        if (!StringUtils.hasText(nameEn)) {
            return false;
        }
        Wrapper<MstrDivision> wrapper = new EntityWrapper<>();
        wrapper.eq("name_en", nameEn).eq("is_deleted", 0);
        List<MstrDivision> divisions = mstrDivisionMapper.selectList(wrapper);
        return !divisions.isEmpty();
    }
} 